package xing.application.service.user;

import com.querydsl.core.types.Path;
import com.vdurmont.emoji.EmojiParser;
import jdk.nashorn.internal.codegen.CompilerConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import xing.application.service.BaseService;
import xing.domain.user.QUser;
import xing.domain.user.User;
import xing.infrastructure.data.CallResult;
import xing.infrastructure.util.StringUtil;
import xing.repository.user.UserRepository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/********************************
 * 文 件 名 :UserService.java
 * 创 建 人：陈天龙
 * 日    期：2017/10/19
 * 描   述：用户业务处理层
 * 版 本 号：v1.0.0
 ********************************/
@Service
public class UserService extends BaseService {

    @Autowired
    private UserRepository userRepository;

    /**
     * 描    述: 新增/更新用户
     * 创 建 人：陈天龙
     * 日    期：2017/10/19
     * @param user
     * @return CallResult
     */
    @Transactional(rollbackFor = Exception.class)
    public void addUser(User user){
        Date now = new Date();
        if(!StringUtils.isEmpty(user.getNickName()))
            user.setNickName(EmojiParser.parseToHtmlDecimal(user.getNickName()));
        if(null == userRepository.findOne(user.getOpenId())){
            user.setCreateTime(now);
            user.setUpdateTime(now);
            userRepository.save(user);
        }else{
            user.setUpdateTime(now);
            updateUser(user);
        }
    }
    /**
     * @Description: 获取用户信息
     * @param:   * @param null
     * @Author: dustin
     * @Date: 2017-11-07 15:50
     */
    public User getUserInfo(String openId){
        User u=userRepository.findOne(openId);
        return u;
    }
    private void updateUser(User user){
        QUser quser = QUser.user;
        List<Path<?>> paths = new ArrayList<>();
        List<Object> values = new ArrayList<>();
        paths.add(quser.nickName);values.add(user.getNickName());
        paths.add(quser.gender);values.add(user.getGender());
        paths.add(quser.city);values.add(user.getCity());
        paths.add(quser.province);values.add(user.getProvince());
        paths.add(quser.country);values.add(user.getCountry());
        paths.add(quser.avatarUrl);values.add(user.getAvatarUrl());
        paths.add(quser.updateTime);values.add(user.getUpdateTime());
        queryFactory.update(quser).set(paths,values).where(quser.openId.stringValue().eq(user.getOpenId())).execute();
    }
}
